package com.platform.common.web.exception;

import com.platform.common.exception.BaseException;
import com.platform.common.utils.AjaxUtils;
import com.platform.common.web.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Object baseException(HttpServletRequest request, HttpServletResponse response, Exception e) {
        response.setStatus(HttpServletResponse.SC_OK);
        String errMsg = "系统错误，请联系管理员！";
        String viewName = "error/error";
        if (e instanceof AuthorizationException) {
            errMsg = "暂无权限，请联系管理员";
            viewName = "error/unauthorized";
        } else if (e instanceof BaseException) {
            errMsg = e.getMessage();
        }
        log.error(e.getMessage(), e);
        if (AjaxUtils.isAjax(request)) {
            return AjaxResult.fail(errMsg);
        }
        ModelAndView mav = new ModelAndView();
        mav.setViewName(viewName);
        return mav;
    }

}
